<?php

	class Backend_CronController extends Zend_Controller_Action {
		
		public function init() {
			if (Zend_Registry::isRegistered('clientserver')) {
				$this->_clientserver = Zend_Registry::get('clientserver');
			
				$this->_apikey = $this->_clientserver->richcore->key;
				//annuaire
				$this->_annuaire = new RichCongress_Rest_Service_RichAnnuaire_Client($this->_clientserver->richannuaire->uri);
				$this->_annuaire->setApiKey($this->_apikey);
				//richcore
				$this->_richcore = new RichCongress_Rest_Service_RichCore_Client($this->_clientserver->richcore->uri);
				$this->_richcore->setApiKey($this->_apikey);
				
	        } else {
	        	throw new Zend_Exception('[ Model_Authentication_Richcore ] unable to find your client server...');
	        }
		}
	
		/**
		 * Users' management formular
		 *
		 * @return html
		 *
		 */
		public function sendmailtovalidatorsAction() {
			$ugM = new Model_UsersGroups();
			$eM = new Model_EmailsManager();
			
			// get all waiting and renewall users
			$filters['name'] = array('waiting', 'waiting_icf', 'renewall', 'renewall_icf');
			$order = array('name');
			$groups = $ugM->get($filters, $order);
			//pre($groups, 'dump');
			
			// get all linked validators
			$filters_validator['name'] = array('validator', 'validator_icf');
			$validators = array();
			$structures = array();
			$users = array();
			
			// email
			$object = 'waiting_demands';
			$report = '';
			
			// translation
			$translate = array('waiting' => 'Inscription',
								'waiting_icf' => 'Inscription ICF',
								'renewall' => 'Renouvellement',
								'renewall_icf' => 'Renouvellement ICF'
								);
			
			foreach($groups AS $g) {
				if(!isset($structures[$g['id_structure']])) {
					
					$structure_temp = $this->_annuaire->get('structure', $g['id_structure']);
					$structures[$g['id_structure']] = $structure_temp[0];
					
					// get all linked validators
					$filters_validator['id_structure'] = $g['id_structure'];
					$filters_validator['name'] = array('validator', 'validator_icf');
				
					// get structure's details
					$validators_temp = $ugM->get($filters_validator);
				
					$parent_temp = $this->_annuaire->getparents($g['id_structure']);
					$parent = $parent_temp[0];
			
					// If establishment, search parent's department
					if($parent['name'] == 'ACADEMIE' or $parent['name'] == 'DEPARTEMENT') {
						$echelon = $parent['name'].' : '.$structure_temp[0]['name'];
				
					} else if(is_null($parent)){
						$echelon = $structure_temp[0]['name'];
			
					} else {
						$parent_temp = $this->_annuaire->getparents($parent['id']);
						$echelon = $parent_temp[0]['name'].' > '.$parent['name'].' : '.$structure_temp[0]['name'];
			
					}
					
					// save echelon
					$structures[$g['id_structure']]['echelon'] = $echelon;
				}
				
				// get user
				if(!isset($users[$g['id_user']])) {
					$temp = $this->_richcore->get('user', $g['id_user']);
					$users[$g['id_user']] = $temp[0];
				}
				$structures[$g['id_structure']]['demands'][$g['name']][] = $users[$g['id_user']];
				
				//echo '==================== structure '.$g['id_structure'].' :<br />';
				foreach($validators_temp AS $vt) {
					if(!isset($validators[$vt['id_user']])) {
						$temp = $this->_richcore->get('user', $vt['id_user']);
						$validators[$vt['id_user']] = $temp[0];
					}
					
					$structures[$g['id_structure']]['validators'][$g['id_user']] = $validators[$vt['id_user']];
					
					//$report .= $translate[$g['name']].' : '.$temp[0]['login'].' '.$g['id_user'].'-'.$temp[0]['id'].'<br />';
					
					$emails[] =  $temp[0]['login'];
					/*
					// send mail
					$to = $temp[0]['login'];
					// TEST
					$to = 'publicite@micster.fr';
				
					if($eM->mail($to, $object)) {
						echo $stranslate[$g['name']].' : '.$temp[0]['login'].' (envoyé)<br />';
				
					} else {
						echo $stranslate[$g['name']].' : '.$temp[0]['login'].' (non envoyé)<br />'
				
					}
					*/
				}
			}
			//pre($structures);
			
			$report .= 'Valideurs contactés :';
			$report .= '<p>';
			foreach($validators AS $v) {
				$report .= $v['login'].'<br />';
			}
			$report .= '</p>';
			$report .= '<p></p><p></p>';
			
			$report .= '<p>======================</p>';
				
			foreach($structures AS $s) {
				$report .= $s['echelon'].'<br />';
				/*
				$report .= 'Valideurs :<br />';
				foreach($s['validators'] AS $id => $login) {
					$report .= $login.'<br />';
				}
				*/
				foreach($s['demands'] AS $d => $tab) {
					$report .= '<p>';
					$report .= $translate[$d].' : '.count($d).' demande';
					$report .= count($d == 1) ? '' : 's';
					$report .= '</p>';
				}
				$report .= '<p>======================</p>';
			}
			
			echo $report;
			
			// send mail to Mickael
			$to = 'meuranie@richcongress.com';
			$object = 'send_report';
			if($eM->send($to, $object, $report)) {
				echo 'Rapport envoyé';
			
			} else {
				echo 'Erreur lors de l\'envoie du rapport';
			}
			
			exit();
			
			
		}
		
		/*
		 * Get waiting demands and renewall to next validator if waiting for more than 7 days
		 *
		 */
		public function updatedemandsAction() {
			$ugM = new Model_UsersGroups();
			
			// get all waiting and renewall users
			$filters['name'] = array('waiting', 'waiting_icf', 'renewall', 'renewall_icf');
			$order = array('name');
			$groups = $ugM->get($filters, $order);
			
			// get the uppermost echelon for each user
			$users = array();
			foreach($groups as $g) {
				if(!isset($users[$g['id_user']])) {
					$users[$g['id_user']] = $g;
				
				} else {
					if($g['id_structure'] < $users[$g['id_user']]['id_structure']) {
						$users[$g['id_user']] = $g;
					}
				}
			}
			
			// check date for each user
			$today = time();
			foreach($users as $u) {
				// check if date > 7 days
				$date_temp = explode(' ', $u['date']);
				$date_tab = explode('-', $date_temp[0]);
				$date = mktime(0, 0, 0, $date_tab[1], $date_tab[2], $date_tab[0]);
				$diff = $today - $date;
				$days = ceil($diff / (3600 * 24));
				
				if($days > 7) {
					
					// get structure's parent
					$parent = 3;	// default : Apel Nationale
					$parent_structures = $this->_annuaire->getparents($u['id_structure']);
					
					// Apel Nationale
					if(count($parent_structures) == 0) {
						$parent = 3;
					
					} else if(count($parent_structures) == 2) {
						
						// departments
						if($parent_structures[0]['id'] == 2) {
							$parent = $parent_structures[1]['id'];
						
						} else if($parent_structures[1]['id'] == 2) {
							$parent = $parent_structures[0]['id'];
						}
						
					// others
					} else {
						$parent = $parent_structures[0]['id'];
					
					}
					
					if($parent < $u['id_structure']) {
						// add entry in apel_workflow.users_groups
						$ugM->insert(array('id_user' => $u['id_user'],
										'name' => ($parent == 3) ? 'waiting' : $u['name'],
										'id_structure' => $parent,
										'date' => date('Y-m-d H:i:s', time())
										));
					}
					
					echo $u['id_user'] . ' : ' . $u['id_structure'] . ' -> ' . $parent . '<br />';
				}
			}
			
			exit();
		}
		
		/*
		 * User's renewall
		 */
		
		public function renewallAction() {
			$ugM = new Model_UsersGroups();
			$rights = $this->_richcore->rights();
			
			// get all validators
			$filters['name'] = array('validator', 'validator_icf');
			$validators_temp = $ugM->get($filters);
			
			$validators = array();
			foreach($validators_temp as $v) {
				if(!in_array($v['id_user'], $validators)) {
					$validators[] = $v['id_user'];
				}
			}
			//Zend_Debug::Dump($validators);
			
			// get all accepted users
			$filters['name'] = array('accepted');
			$order = array('name');
			$groups = $ugM->get($filters, $order);
			
			// get the uppermost echelon for each user
			$users = array();
			foreach($groups as $g) {
				if(!isset($users[$g['id_user']])) {
					$users[$g['id_user']] = (int)$g['id_structure'];
				
				} else {
					if($g['id_structure'] < $users[$g['id_user']]) {
						$users[$g['id_user']] = (int)$g['id_structure'];
					}
				}
			}
			
			// add each distinct user in waiting_renewall[_icf] group
			foreach($users as $id_user => $id_structure) {
				// check if administrator or not
				// $rights = $this->_richcore->rights($id_user);
				// Zend_Debug::Dump($userrights); exit;
				
				// check groups to know if icf or not
				$infos = $this->_annuaire->getpersonbyuserid($id_user);
				echo $infos[0]['function'].'<br />';
				$functions = Zend_Json::decode($infos[0]['function']);
				$icf = false;
				if(is_array($functions) and !empty($functions)) {
				echo 'toto'; exit;
				foreach($functions as $f) {
					if($f == 'Animateur_BDI') {
						$icf = true;
					}
				}
				} else {
					echo $functions.'<br />';
					if($functions == 'Animateur_BDI') {
						$icf = true;
					}
				}
				Zend_Debug::Dump($icf);
			}
			
			
			
			exit();
		}
	}
	
?>
